package com.example.hotel_lxy.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.application.ARouterPath;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.CustomerDetailsBean;
import com.example.hotel_lxy.bean.CustomerDetailsHistoryBean;
import com.example.hotel_lxy.bean.ImgBean;
import com.example.hotel_lxy.bean.JsonBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.toll.GetJsonDataUtil;
import com.example.hotel_lxy.ui.dialog.DialPhoneDialog;
import com.example.hotel_lxy.ui.dialog.ImageViewpagerDialog;
import com.example.hotel_lxy.ui.dialog.SexDialog;
import com.example.hotel_lxy.utils.GlideEngine;
import com.example.hotel_lxy.utils.JurisdictionUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.example.hotel_lxy.view.ImageViewPlus;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ysxsoft.common_base.adapter.BaseQuickAdapter;
import com.ysxsoft.common_base.adapter.BaseViewHolder;
import com.ysxsoft.common_base.base.BaseActivity;
import com.ysxsoft.common_base.base.RBaseAdapter;
import com.ysxsoft.common_base.base.RViewHolder;
import com.ysxsoft.common_base.base.frame.list.IListAdapter;
import com.ysxsoft.common_base.base.frame.list.ListManager;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.view.custom.image.RoundImageView;
import com.ysxsoft.common_base.view.widgets.MultipleStatusView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 客户详情
 */
@Route(path = "/main/CustomerDetailsActivity")
public class CustomerDetailsActivity extends BaseActivity implements View.OnClickListener, IListAdapter<CustomerDetailsHistoryBean.DataBean.ListBean> {


    @BindView(R.id.text_anniversary)
    TextView textAnniversary;
    @BindView(R.id.text_set)
    TextView textSet;
    @BindView(R.id.edittext_address)
    EditText edittextAddress;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.text_sr)
    TextView textSr;
    @BindView(R.id.frame_gr)
    FrameLayout frameGr;
    @BindView(R.id.edittext_dw)
    EditText edittextDw;
    @BindView(R.id.edittext_zw)
    EditText edittextZw;
    @BindView(R.id.edittext_xh)
    EditText edittextXh;
    @BindView(R.id.edittext_jk)
    EditText edittextJk;
    @BindView(R.id.edittext_bz)
    EditText edittextBz;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.multipleStatusView)
    MultipleStatusView multipleStatusView;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefresh;
    ListManager<CustomerDetailsHistoryBean.DataBean.ListBean> manager;
    boolean aBoolean = false;
    @BindView(R.id.img_src)
    ImageViewPlus imgSrc;
    @BindView(R.id.text_name)
    EditText textName;
    @BindView(R.id.text_sex)
    ImageView textSex;
    @BindView(R.id.text_photo)
    TextView textPhoto;
    @BindView(R.id.rv_return_img)
    RecyclerView rvReturnImg;
    @BindView(R.id.line1)
    LinearLayout line1;
    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private List<String> mlist = new ArrayList<>();
    String token;
    private Thread thread;
    int size;
    String sex = "1";
    String avatar = "";
    private int img_type;// 1 头像  2 其他
    @Autowired
    String id;
    @Autowired
    String type; //1 宴会  2 零点
    @Autowired
    String source_id;
    String other = "";
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();

                            }
                        });
                        thread.start();
                    }
                    break;
            }
        }
    };
    RBaseAdapter<String> rBaseAdapter;
    List<String> image = new ArrayList<>();
    List<String> listid = new ArrayList<>();
//    List<LocalMedia> mediaht = new ArrayList<>();

    public static void start(String id, String type, String source_id) {
        ARouter.getInstance().build(ARouterPath.getCustomerDetailsActivity())
                .withString("id", id)
                .withString("type", type)
                .withString("source_id", source_id)
                .navigation();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_customer_details;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void doWork() {
        super.doWork();
        ARouter.getInstance().inject(this);
        token = SPUtils.get(CustomerDetailsActivity.this, "token", "").toString();
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        showView();
        showDataHiStory();
        showOnClick();
        showDateCheck();
        if (type.equals("1")) {
            boolean modifybanquet = JurisdictionUtils.getModifybanquet(CustomerDetailsActivity.this);
            if (modifybanquet) {
                textSet.setVisibility(View.VISIBLE);
            } else {
                boolean getuserid = JurisdictionUtils.getuserid(CustomerDetailsActivity.this, source_id);
                if (getuserid) {
                    textSet.setVisibility(View.VISIBLE);
                } else {
                    textSet.setVisibility(View.GONE);
                }
            }
        }
        else if (type.equals("2")) {
            boolean modifyzero = JurisdictionUtils.getModifyzero(CustomerDetailsActivity.this);
            if (modifyzero) {
                textSet.setVisibility(View.VISIBLE);
            } else {
                boolean getuserid = JurisdictionUtils.getuserid(CustomerDetailsActivity.this, source_id);
                if (getuserid) {
                    textSet.setVisibility(View.VISIBLE);
                } else {
                    textSet.setVisibility(View.GONE);
                }
            }
        }
    }

    private void showOnClick() {
        textSet.setOnClickListener(this);
        text.setOnClickListener(this);
        textSr.setOnClickListener(this);
        textAnniversary.setOnClickListener(this);
        textPhoto.setOnClickListener(this);
        textSex.setOnClickListener(this);
        imgSrc.setOnClickListener(this);
        line1.setOnClickListener(this);
    }

    private void showView() {
        manager = new ListManager(this);
        manager.init(getWindow().findViewById(android.R.id.content));
        manager.getAdapter().setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
//        manager.getAdapter().setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
//            @Override
//            public void onLoadMoreRequested() {
//                //request(manager.nextPage());
//            }
//        }, recyclerView);
        request(1);
    }

    private void showDataHiStory() {
        String token = SPUtils.get(CustomerDetailsActivity.this, "token", "").toString();
        OkHttpUtils.post()
                .url(Api.POST_CLIENTINFOR)
                .addHeader("flag", token)
                .addParams("id", id + "")
                .addParams("type", type)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户详情onError   " + e.getMessage());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户详情onResponse   " + response);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            CustomerDetailsBean customerDetailsBean = JsonUtils.parseByGson(response, CustomerDetailsBean.class);
                            CustomerDetailsBean.DataBean.ListBean list = customerDetailsBean.getData().getList();
                            if (list.getUnit() != null && !list.getUnit().equals("null") && !list.getUnit().isEmpty()) {
                                edittextDw.setText("" + list.getUnit());
                            }
                            if (list.getPosition() != null && !list.getPosition().equals("null") && !list.getPosition().isEmpty()) {
                                edittextZw.setText("" + list.getPosition());
                            }
                            if (list.getBirthday() != null && !list.getBirthday().equals("null") && !list.getBirthday().isEmpty()) {
                                textSr.setText("" + list.getBirthday());
                            }
                            if (list.getAddress() != null && !list.getAddress().equals("null") && !list.getAddress().isEmpty()) {
                                edittextAddress.setText("" + list.getAddress());
                            }
                            if (list.getLikes() != null && !list.getLikes().equals("null") && !list.getLikes().isEmpty()) {
                                edittextXh.setText("" + list.getLikes());
                            }
                            if (list.getDiet() != null && !list.getDiet().equals("null") && !list.getDiet().isEmpty()) {
                                edittextJk.setText("" + list.getDiet());
                            }
                            if (list.getContent() != null && !list.getContent().equals("null") && !list.getContent().isEmpty()) {
                                edittextBz.setText("" + list.getContent());
                            }
                            if (list.getAvatars() != null && !list.getAvatars().equals("null") && !list.getAvatars().isEmpty()) {
                                avatar = list.getAvatar() + "";
                            }
                            if (list.getName() != null && !list.getName().equals("null") && !list.getName().isEmpty()) {
                                textName.setText("" + list.getName());
                            }
                            if (list.getMobile() != null && !list.getMobile().equals("null") && !list.getMobile().isEmpty()) {
                                textPhoto.setText("" + list.getMobile());
                            }
                            Glide.with(CustomerDetailsActivity.this).load(list.getAvatars()).into(imgSrc);

                            if (list.getSex() != null) {
                                sex = list.getSex();
                            }
                            if (sex.equals("1")) {
                                Glide.with(CustomerDetailsActivity.this).load(R.mipmap.icon_nan).into(textSex);
                            } else {
                                Glide.with(CustomerDetailsActivity.this).load(R.mipmap.icon_nv).into(textSex);
                            }
                            mlist.clear();
                            listid.clear();
                            if (list.getOther() != null) {
                                String[] split = list.getOther().split(",");
                                for (int i = 0; i < split.length; i++) {
                                    listid.add(split[i]);
                                }
                                image = list.getImage();
                            }
//                            String[] split = list.getOther().split(",");
//                            for (int i = 0; i <split.length ; i++) {
//                                listid.add(split[i]);
//                            }
//                            image = list.getImage();
                            showRvImg();
                        } else if (beanBean.getCode().equals("4")) {
                            SPUtils.put(CustomerDetailsActivity.this, "token", "");
                            Intent intent = new Intent(CustomerDetailsActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } else {
                            ToastUtils.s(CustomerDetailsActivity.this, ""+beanBean.getMsg());
                        }

                    }
                });
    }

    private void showRvImg() {
        if (image != null) {
            if (aBoolean) {
                if (mlist.size() + image.size() < 20) {
                    mlist.add(0, "");
                }
            }
            for (int i = 0; i < image.size(); i++) {
                mlist.add(mlist.size(), image.get(i));
            }
        } else {
            if (aBoolean) {
                if (mlist.size() < 20) {
                    mlist.add(0, "");
                }
            }
        }
        rvReturnImg.setLayoutManager(new GridLayoutManager(CustomerDetailsActivity.this, 3));
        rBaseAdapter = new RBaseAdapter<String>(CustomerDetailsActivity.this, R.layout.item_returnvist_img, mlist) {
            @Override
            protected void fillItem(RViewHolder holder, String item, int position) {
                RoundImageView img = holder.itemView.findViewById(R.id.img_round);
                ImageView img_detele = holder.itemView.findViewById(R.id.img_detele);
                if (!item.equals("")) {
                    if (aBoolean) {
                        img_detele.setVisibility(View.VISIBLE);
                    } else {
                        img_detele.setVisibility(View.GONE);
                    }
                    Glide.with(CustomerDetailsActivity.this).load(item).into(img);
                } else {
                    if (aBoolean) {
                        img.setVisibility(View.VISIBLE);
                    } else {
                        img.setVisibility(View.GONE);
                    }
                    img_detele.setVisibility(View.GONE);
                    Glide.with(CustomerDetailsActivity.this).load(R.mipmap.icon_rv_img).into(img);
                }

                img_detele.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (item.contains("http")) {
                            for (int i = 0; i < image.size(); i++) {
                                if (image.get(i).equals("" + item)) {
                                    image.remove(i);
                                    listid.remove(i);
                                }
                            }
                            if (mlist.get(position).equals(item)) {
                                mlist.remove(position);
                            }
                        } else {
                            if (mlist.get(position).equals(item)) {
                                mlist.remove(position);
                            }
                        }
                        if (mlist.size() < 20) {
                            if (!mlist.contains("")) {
                                mlist.add(0, "");
                            }
                        }
                        notifyDataSetChanged();
                    }
                });
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (item.equals("")) {
                            showImg();
                        } else {
                            if(mlist.size()!=20){
                                ImageViewpagerDialog.show(CustomerDetailsActivity.this, null, mlist, position - 1);
                            }else{
                                ImageViewpagerDialog.show(CustomerDetailsActivity.this, null, mlist, position );
                            }

                        }
                    }
                });
            }

            @Override
            protected int getViewType(String item, int position) {
                return 0;
            }
        };
        rvReturnImg.setAdapter(rBaseAdapter);
    }

    private void showImg() {
        img_type = 2;
        if (mlist.get(0).equals("")) {
            mlist.remove(0);
        }
        int i = 20 - Integer.valueOf(mlist.size());
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .selectionMode(100)
                .maxSelectNum(i)
                .previewImage(true)
                .compress(true)//图片是否压缩
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_set:
                if (aBoolean) {
                    if ((mlist.size() - 1) == 0) {
                        showDataSave(other);
                    } else {
                        initUploadHT();
                    }
                    textSet.setText("编辑");
                    aBoolean = false;
                } else {
                    textSet.setText("保存");
                    aBoolean = true;
                    mlist.clear();
                    showRvImg();
                }
//                if (rBaseAdapter != null) {
//                    rBaseAdapter.notifyDataSetChanged();
//                }
                showDateCheck();

                break;
            case R.id.text:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                boolean isOpen = imm.isActive();
                if (isOpen) {
                    InputMethodManager inputMethodManager = (InputMethodManager) CustomerDetailsActivity.this.getSystemService(Activity.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
                showPickerView();
                break;
            case R.id.text_sr:
                InputMethodManager imms = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                boolean isOpens = imms.isActive();
                if (isOpens) {
                    InputMethodManager inputMethodManager = (InputMethodManager) CustomerDetailsActivity.this.getSystemService(Activity.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
                showTimePickerView();
                break;
            case R.id.text_anniversary: //纪念日
                AnniversaryActivity.start(id);
                break;
            case R.id.text_photo://拨打手机号
                if (isPhone(textPhoto.getText().toString())) {
//                    Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_CALL);
//                    intent.setData(Uri.parse("tel:" + textPhoto.getText().toString()));
//                    startActivity(intent);
                    DialPhoneDialog.show(CustomerDetailsActivity.this,null,textPhoto.getText().toString()+"");
                } else {
                    ToastUtils.s(CustomerDetailsActivity.this, "手机号有误");
                }
                break;
            case R.id.text_sex:
                SexDialog.show(CustomerDetailsActivity.this, null).setListener(new SexDialog.OnDialogClickListener() {
                    @Override
                    public void onPositiveClick(String s) {
                        sex = s;
                        if (s.equals("1")) {
                            Glide.with(CustomerDetailsActivity.this).load(R.mipmap.icon_nan).into(textSex);
                        } else {
                            Glide.with(CustomerDetailsActivity.this).load(R.mipmap.icon_nv).into(textSex);
                        }
                    }
                });
                break;
            case R.id.img_src:
                img_type = 1;
                PictureSelector.create(CustomerDetailsActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .selectionMode(100)
                        .maxSelectNum(1)
                        .isEnableCrop(true)
                        .previewImage(true)
                        .circleDimmedLayer(true)
                        .showCropFrame(false)
                        .isZoomAnim(false)
                        .showCropGrid(false)
                        .scaleEnabled(true)
                        .rotateEnabled(false)
                        .withAspectRatio(7, 7)
                        .compress(true)//图片是否压缩
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.line1:
                edittextBz.setFocusable(true);
                edittextBz.setFocusableInTouchMode(true);
                edittextBz.requestFocus();
                initInput();
                break;
        }
    }

    private void initInput() {
        InputMethodManager inputManager = (InputMethodManager) edittextBz.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(edittextBz, 0);
    }

    private void initUploadHT() {

        PostFormBuilder builder1 = OkHttpUtils.post()
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .url(Api.POSY_UPLOADS);

        String path1 = avatar;
        if (path1 != null && !path1.isEmpty()) {
            File file = new File(path1);
            builder1.addFile("file[]", file.getName(), file);
        }

        showLoadingDialog();
        builder1.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                initTU();
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                ImgBean imgBean = JsonUtils.parseByGson(response, ImgBean.class);
                if (imgBean.getCode().equals("0")) {
                    for (int i = 0; i < imgBean.getData().size(); i++) {
                        ImgBean.DataBean dataBean = imgBean.getData().get(i);
                        avatar = dataBean.getId();
                        initTU();
                    }
                }

            }
        });

    }

    private void initTU() {
        List<String> mlistq = new ArrayList<>();
        for (int i = 0; i < mlist.size(); i++) {
            if (!mlist.get(i).equals("")) {
                if (!mlist.get(i).contains("http")) {
                    mlistq.add(mlist.get(i));
                }
            }
        }
        if (mlistq.size() == 0) {
            StringBuffer sb1 = new StringBuffer();
            for (int i = 0; i < listid.size(); i++) {
                sb1.append(listid.get(i) + ",");
            }
            if (!sb1.toString().equals("")) {
                other = sb1.toString();
            }
            if (!other.equals("")) {
                showDataSave(other.substring(0, sb1.toString().length() - 1));
            }
            return;
        }
        PostFormBuilder builder = OkHttpUtils.post()
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .url(Api.POSY_UPLOADS);
        for (int i = 0; i < mlistq.size(); i++) {
            String path = mlistq.get(i);
            if (path != null && !path.isEmpty()) {
                File file = new File(path);
                builder.addFile("file[]", file.getName(), file);
            }
        }
        showLoadingDialog();
        builder.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                ImgBean imgBean = JsonUtils.parseByGson(response, ImgBean.class);
                StringBuffer sb = new StringBuffer();
                if (imgBean.getCode().equals("0")) {
                    for (int i = 0; i < imgBean.getData().size(); i++) {
                        ImgBean.DataBean dataBean = imgBean.getData().get(i);
                        sb.append(dataBean.getId() + ",");
                    }
                    if (!sb.toString().equals("")) {
                        other = sb.toString();
                    }
                    StringBuffer sb1 = new StringBuffer();
                    for (int i = 0; i < listid.size(); i++) {
                        if(!listid.get(i).equals("")){
                            sb1.append(listid.get(i) + ",");
                        }
                    }
                    if (!sb1.toString().equals("")) {
                        other = sb.toString() + sb1.toString();
                    }
                }
                if (!other.equals("")) {
                    showDataSave(other.substring(0, other.length() - 1));
                }
            }
        });
    }

    private void showDataSave(String other) {
        OkHttpUtils.post()
                .url(Api.POST_SAVE)
                .addHeader("flag", token)
                .addParams("id", id + "")
                .addParams("name", textName.getText().toString() + "")
                .addParams("avatar", avatar + "")
                .addParams("unit", edittextDw.getText().toString())
                .addParams("position", edittextZw.getText().toString() + "")
                .addParams("address", edittextAddress.getText().toString())
                .addParams("birthday", textSr.getText().toString() + "")
                .addParams("likes", edittextXh.getText().toString())
                .addParams("diet", edittextJk.getText().toString() + "")
                .addParams("content", edittextBz.getText().toString())
                .addParams("other", other)
                .addParams("sex", sex + "")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户详情保存onError   " + e.getMessage());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户详情保存onResponse   " + response);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            showDataHiStory();
                            request(1);
                        } else if (beanBean.getCode().equals("4")) {
                            SPUtils.put(CustomerDetailsActivity.this, "token", "");
                            Intent intent = new Intent(CustomerDetailsActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }

                    }
                });
    }

    private void showTimePickerView() {
        Calendar c = Calendar.getInstance();//
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(0000, 0, 0);
        Calendar endDate = Calendar.getInstance();
        endDate.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));
        //时间选择器
        @SuppressLint("ResourceAsColor")
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                textSr.setText(getTimes(date));
            }
        })

                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "时", "", "")
                .isCenterLabel(true)
                .setDividerColor(R.color.color_1B96F8)
                .setContentTextSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .build();
        pvTime.show();

    }

    private String getTimes(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    //选择城市
    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).toString() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + "" + opt2tx + "" + opt3tx;
                edittextAddress.setText("" + tx);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

//        /*pvOptions.setPicker(options1Items);//一级选择器
//        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void showDateCheck() {
        edittextDw.setEnabled(aBoolean);
        edittextZw.setEnabled(aBoolean);
        edittextAddress.setEnabled(aBoolean);
        text.setEnabled(aBoolean);
        textSr.setEnabled(aBoolean);
//        textAnniversary.setEnabled(aBoolean);
        edittextXh.setEnabled(aBoolean);
        edittextJk.setEnabled(aBoolean);
        edittextBz.setEnabled(aBoolean);
        textName.setEnabled(aBoolean);
        textSex.setEnabled(aBoolean);
        imgSrc.setEnabled(aBoolean);
        textPhoto.setEnabled(aBoolean);
        line1.setEnabled(aBoolean);
    }

    //添加省份数据
    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);

                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    public int getItemLayoutId() {
        return R.layout.item_customerdetails_activity;
    }

    @Override
    public void request(int page) {
        OkHttpUtils.post()
                .url(Api.POST_USERORDER)
                .addHeader("flag", token)
                .addParams("id", id + "")
                .addParams("page", page + "")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户详情历史onError   " + e.getMessage());
                        manager.releaseRefresh();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户详情历史onResponse   " + response);
                        manager.releaseRefresh();
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("4")) {
                            SPUtils.put(CustomerDetailsActivity.this, "token", "");
                            Intent intent = new Intent(CustomerDetailsActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        CustomerDetailsHistoryBean customerDetailsHistoryBean = JsonUtils.parseByGson(response, CustomerDetailsHistoryBean.class);
                        size = customerDetailsHistoryBean.getData().getList().size();
                        if (beanBean.getCode().equals("0")) {
                            if(page==1){
                                manager.resetPage();
                            }
                            manager.setData(customerDetailsHistoryBean.getData().getList());
                        }
                    }
                });
    }

    @Override
    public void fillView(BaseViewHolder helper, CustomerDetailsHistoryBean.DataBean.ListBean s) {
        TextView text_number = helper.itemView.findViewById(R.id.text_number);
        TextView text_is_meeting = helper.itemView.findViewById(R.id.text_is_meeting);
        TextView text_scheduled_time = helper.itemView.findViewById(R.id.text_scheduled_time);
        TextView text_start_time = helper.itemView.findViewById(R.id.text_start_time);
        int layoutPosition = helper.getLayoutPosition();
        layoutPosition = size - layoutPosition;
        text_number.setText("" + layoutPosition);
        if (s.getIs_meeting() == 1) {
            text_is_meeting.setText("【" + s.getBanquet() + "】会议 " + s.getDesk() + "人 ");
        } else {
            text_is_meeting.setText("【" + s.getBanquet() + "】" + s.getBanquet_type() + " " + s.getDesk() + "桌备" + s.getPrepare_desk() + "桌");
        }
        text_scheduled_time.setText(" 预订日期：" + s.getScheduled_time());
        text_start_time.setText(" 宴会日期：" + s.getStart_time());
        helper.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReserveInformationActivity.start(s.getId() + "", "");
            }
        });
    }

    @Override
    public void fillMuteView(BaseViewHolder helper, CustomerDetailsHistoryBean.DataBean.ListBean s) {

    }

    @Override
    public void attachActivity(AppCompatActivity activity) {

    }

    @Override
    public void dettachActivity() {

    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(this);
    }

    @Override
    public boolean isMuteAdapter() {
        return false;
    }

    @Override
    public int[] getMuteTypes() {
        return new int[0];
    }

    @Override
    public int[] getMuteLayouts() {
        return new int[0];
    }

    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(167)|(165)|(17[0,1,2,3,5,6,7,8])|(18[0-9])|(19[0-9]))\\d{8}$";
       // String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {

            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
            if (localMedia != null) {
                if (img_type == 1) {
                    avatar = localMedia.get(0).getCompressPath();
                    Glide.with(CustomerDetailsActivity.this).load(localMedia.get(0).getCompressPath()).into(imgSrc);
                } else {
                    if (mlist.size() != 0) {
                        if (mlist.get(0).equals("")) {
                            mlist.remove(0);
                        }
                    }
                    if (mlist.size() != 0) {
                        for (int i = mlist.size() - 1; i >= 0; i--) {
                            if (mlist.get(i).contains("http")) {
                                mlist.remove(i);
                            }
                        }
                    }
                    for (int i = 0; i < localMedia.size(); i++) {
                        mlist.add(localMedia.get(i).getCompressPath());
                    }
                    showRvImg();
                }
            }
        }
    }

}